//
//  MusicPlayViewController.m
//  LO_MUSIC
//
//  Created by lanou3g on 16/2/26.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "MusicPlayViewController.h"
#import "RequestURL.h"
#import "AudioPlayer.h"
#import <UIImageView+WebCache.h>
#import "LyTool.h"
static   NSInteger indexP ;
@interface MusicPlayViewController ()<AudioPlayerDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) MusicModel *currentMusicModel;
@property (weak, nonatomic) IBOutlet UIImageView *imageV;//图片
@property (nonatomic,strong)AudioPlayer *audioPlayer;
@property (weak, nonatomic) IBOutlet UILabel *endTime;//结束时间
@property (weak, nonatomic) IBOutlet UILabel *startTime;//开始时间
@property (weak, nonatomic) IBOutlet UIButton *playOrPause;
@property (weak, nonatomic) IBOutlet UISlider *timeSlider;
@property (weak, nonatomic) IBOutlet UISlider *volumeSlider;
//当前播放的下标
@property (nonatomic,strong)NSIndexPath *singingIndex;
- (void)updateUI;
- (void)startPlaying;
@end


@implementation MusicPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    indexP = _indexPath.row;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.audioPlayer.delegate = self;
    self.imageV.layer.cornerRadius = 107.5;
    self.imageV.layer.masksToBounds = YES;
    
    [self.timeSlider addTarget:self action:@selector(timeSliderAction:) forControlEvents:UIControlEventValueChanged];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    //处理歌词
    LyTool *lytool = [LyTool shareLyTool];
    [lytool lyerWithStr:self.currentMusicModel.lyric];
    
    [self startPlaying];
    
}
/*
//-(void)viewWillAppear:(BOOL)animated{
//    
//    [self startPlaying];
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//    [self becomeFirstResponder];
//}
//- (void)viewDidDisappear:(BOOL)animated
//{
//    //    [super viewDidDisappear:animated];
//    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
//    [self resignFirstResponder];
//}

*/
- (void)updateUI
{
    
    MusicModel *model = self.modelArray[indexP];
    self.title = model.name;

    [self.audioPlayer playWithUrl:model.mp3Url];
    
    LyTool *lytool = [LyTool shareLyTool];
    [lytool lyerWithStr:model.lyric];
    // 显示图片
    [self.imageV sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
    // 修改时间进度条最大值
    self.timeSlider.maximumValue = [model.duration floatValue] / 1000;
    self.endTime.text = [self timeStrFromTime:[model.duration floatValue]/1000];
    [self.tableView reloadData];
}
- (void)startPlaying
{
    [self updateUI];
    [self.playOrPause setTitle: @"暂 停" forState:(UIControlStateNormal)];
}
//播放结束
-(void)playFinish{
    [self Next:nil];
}
//播放中
-(void)playWithTime:(CGFloat)time;{
    
      self.timeSlider.value = time;
      MusicModel *model = self.modelArray[indexP];
      self.startTime.text = [self timeStrFromTime:time];
      self.endTime.text = [self timeStrFromTime:([model.duration integerValue] / 1000 - time)];
    
      //现在应该执行哪句歌词
      NSInteger index = [[LyTool shareLyTool] indexForTime:time];
      //获取到当前播放歌词的下标
      if (index > 0) {
          self.singingIndex = [NSIndexPath indexPathForRow:index inSection:0];
          
          [self.tableView scrollToRowAtIndexPath:self.singingIndex atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
          [self.tableView reloadData];
      }else{
          
          self.singingIndex = [NSIndexPath indexPathForRow:0 inSection:0];
          [self.tableView scrollToRowAtIndexPath:self.singingIndex atScrollPosition:(UITableViewScrollPositionMiddle) animated:NO];
          [self.tableView reloadData];
      }
}
/**
 *  时间进度条方法
 */
- (void)timeSliderAction:(UISlider *)sender
{
    // 修改播放器的播放事件
//    NSLog(@"%f", sender.value);
    [self.audioPlayer seekToWithTime:sender.value];
}
- (IBAction)volumeSliderAction:(UISlider *)sender {
        self.audioPlayer.volume = sender.value;
}
//上一首
- (IBAction)Previous:(id)sender {
    if (indexP == 0) {
        indexP = self.modelArray.count-1;
    }else{
        indexP--;
    }
    self.audioPlayer.volume = self.volumeSlider.value;
    [self startPlaying];
}
//暂停/播放
- (IBAction)Pause:(UIButton *)sender {
    if (self.audioPlayer.isPlaying) {
        [self.playOrPause setTitle: @"播 放" forState:(UIControlStateNormal)];
    }else{
        [self.playOrPause setTitle: @"暂 停" forState:(UIControlStateNormal)];
    }
    // 状态取反
//    sender.selected = !sender.isSelected;
    [self.audioPlayer playOrPause];
}
//下一首
- (IBAction)Next:(id)sender {
    self.audioPlayer.volume = self.volumeSlider.value;
    [self.tableView reloadData];
    if (indexP >= self.modelArray.count-1) {
        indexP = 0;
    }else{
        indexP++;
    }
    [self startPlaying];
}
//停止
- (IBAction)Stop:(id)sender {
    [self.playOrPause setTitle: @"播 放" forState:(UIControlStateNormal)];
    [self.audioPlayer stop];
}
//下载
- (IBAction)downloadMusic:(id)sender {
    
}

//暂停下载
- (IBAction)pauseDownload:(id)sender {
    
}
//继续下载
- (IBAction)continueDownload:(id)sender {
    
}
/**
 *  时间转字符串
 *
 *  @param time 秒数
 *
 *  @return 返回的字符串
 */
- (NSString *)timeStrFromTime:(float)time
{
    int minutes = time / 60;
    int second = (int)time % 60;
    
    return [NSString stringWithFormat:@"%02d:%02d", minutes, second];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [LyTool shareLyTool].modelArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableView"];

    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"UITableView"];
    }
    LyTool*model = [LyTool shareLyTool].modelArr[indexPath.row];
    cell.textLabel.text = model.ly;
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    if (self.singingIndex == indexPath) {
        cell.textLabel.font = [UIFont systemFontOfSize:22];
        cell.textLabel.numberOfLines = 2;
    }else{
        cell.textLabel.font = [UIFont systemFontOfSize:17];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(AudioPlayer *)audioPlayer{    
    if (!_audioPlayer) {
        _audioPlayer = [AudioPlayer shareAudioPlayer];
    }
    return _audioPlayer;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
